#include <mcus/esp8266/stdinc.h>
#include "http.h"

#define LOGTAG "SZW:HTTP"


static void httpCleanup(esp_http_client_handle_t client) {
    esp_http_client_close(client);
    esp_http_client_cleanup(client);
}

esp_err_t httpGet(const char *url, char *buf, int *len, http_event_handle_cb eventHandler) {
	esp_err_t err;
    esp_http_client_config_t config = {
        .url = url,
        .event_handler = eventHandler,
    };

    esp_http_client_handle_t client = esp_http_client_init(&config);
    if (client == NULL) {
        loge("Failed to initialise HTTP connection");
        return ESP_FAIL;
    }

    err = esp_http_client_open(client, 0);
    if (err != ESP_OK) {
        esp_http_client_cleanup(client);
        loge("Failed to open HTTP connection: %d", err);
        return err;
    }

    esp_http_client_fetch_headers(client);
    int code = esp_http_client_get_status_code(client);
    if(code != 200) {
        httpCleanup(client);
        return ESP_ERR_INVALID_STATE;
    }

	*len = esp_http_client_read(client, buf, *len);
	buf[*len] = '\0';
    logd("body len = %d", *len);

    httpCleanup(client);
    return err;
}
